package com.marvels.loanapply.channel.service.impl;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.marvels.common.dto.UserDTO;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.CacheUtils;
import com.marvels.common.utils.CommonProperties;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.common.utils.ServerProperties;
import com.marvels.loanapply.channel.dao.UserChannelRelationMapper;
import com.marvels.loanapply.channel.dao.UserMarvelChannelInfoMapper;
import com.marvels.loanapply.channel.dto.ChannelUserListParamDTO;
import com.marvels.loanapply.channel.dto.ChannelUserListResultDTO;
import com.marvels.loanapply.channel.dto.SysUserDTO;
import com.marvels.loanapply.channel.dto.SysUserParamDTO;
import com.marvels.loanapply.channel.dto.UserChannelInfo;
import com.marvels.loanapply.channel.dto.UserChannelInfoParamDTO;
import com.marvels.loanapply.channel.dto.UserChannelInfoResultDTO;
import com.marvels.loanapply.channel.dto.UserChannelRelation;
import com.marvels.loanapply.channel.dto.UserChannelRelationDTO;
import com.marvels.loanapply.channel.service.UserChannelInfoService;
import com.marvels.loanapply.consum.LoanapplyConsumerSystemApi;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;

@Service
public class UserChannelInfoServiceImpl implements UserChannelInfoService {

	@Autowired
	private UserMarvelChannelInfoMapper UserMarvelChannelInfoMapper;
	
	@Autowired
	private UserChannelRelationMapper userChannelRelationMapper;
	
	@Autowired
	private LoanapplyConsumerSystemApi consumerSystemApi;
	/*private String adminName = "admin";
	private String adminCode = "admin";*/
	
	@Value("${config.properties.path}")
	private String configPropertiesPath;
	
	@Override
	public void insertUserChannelInfo(UserChannelInfoParamDTO userChannelInfoParamDTO)
			throws MarvelsBusinessException {
		try {
			System.out.println(CommonProperties.getBhSftpHost());
			if(StrUtil.isEmpty(userChannelInfoParamDTO.getChannelName())){
				throw new MarvelsBusinessException("渠道名称不能为空");
			}
			if(StrUtil.equals(userChannelInfoParamDTO.getChannelName(), "自然流量")){
				throw new MarvelsBusinessException("渠道名称不合法");
			}
			List<UserChannelInfoResultDTO> list = UserMarvelChannelInfoMapper.queryUserChannelList(userChannelInfoParamDTO);
			if(list.size() > 0){
				throw new MarvelsBusinessException("渠道名称已被占用");
			}
			UserChannelInfo userChannelInfo = new UserChannelInfo();
			String channelCode = this.generatChannelCode();
			userChannelInfo.setChannelCode(channelCode);
			userChannelInfo.setCpa(userChannelInfoParamDTO.getCpa());
			userChannelInfo.setChannelName(userChannelInfoParamDTO.getChannelName());
			String channelBaseUrl  = ServerProperties.getValue(configPropertiesPath, "common.properties", "channel_base_url");
			userChannelInfo.setChannelBaseUrl(String.format(channelBaseUrl, channelCode));
			//新增渠道
			int number = UserMarvelChannelInfoMapper.insertSelective(userChannelInfo);
			//新增用户渠道关联
			UserDTO user = CacheUtils.getCacheUser();
			UserChannelRelation userChannelRelation = new UserChannelRelation();
			userChannelRelation.setChannelCode(channelCode);
			userChannelRelation.setRealName(user.getRealName());
			userChannelRelation.setUserCode(user.getUserCode());
			userChannelRelationMapper.insertSelective(userChannelRelation);
			//新增管理员关联
			if(!user.getUserCode().equals(this.defaultRelationUser())){
				UserChannelRelation adminRelation = new UserChannelRelation();
				adminRelation.setChannelCode(channelCode);
				adminRelation.setRealName(this.defaultRelationUser());
				adminRelation.setUserCode(this.defaultRelationUser());
				userChannelRelationMapper.insertSelective(adminRelation);
			}
			if(number == 0){
				throw new MarvelsBusinessException("未插入成功");
			}
		} catch (Exception e) {
			throw new MarvelsBusinessException(e);
		}
	}

	@Override
	public UserChannelInfoResultDTO operateChannelStatus(UserChannelInfoParamDTO userChannelInfoParamDTO)
			throws MarvelsBusinessException {
		try {
			String channelCode = userChannelInfoParamDTO.getChannelCode();
			Integer status = userChannelInfoParamDTO.getStatus();
			String channelName = userChannelInfoParamDTO.getChannelName();
			if(StrUtil.isEmpty(channelCode)){
				throw new MarvelsBusinessException("参数错误");
			}
			//查询操作实体
			UserChannelInfo userChannelInfo = UserMarvelChannelInfoMapper.queryUserChannelByCode(channelCode);
			userChannelInfo.setStatus(status);
			userChannelInfo.setChannelName(channelName);
			UserMarvelChannelInfoMapper.updateByPrimaryKeySelective(userChannelInfo);
			return this.queryUserChannelDtoByCode(userChannelInfoParamDTO);
		} catch (Exception e) {
			throw new MarvelsBusinessException(e);
		}
	}

	@Override
	public List<UserChannelInfoResultDTO> queryUserChannelList(UserChannelInfoParamDTO userChannelInfoParamDTO)
			throws MarvelsBusinessException {
		try {
			UserDTO user = CacheUtils.getCacheUser();
			userChannelInfoParamDTO.setUserCode(user.getUserCode());
			PageHelper.startPage(userChannelInfoParamDTO.getPageNo(), userChannelInfoParamDTO.getPageSize());
			return UserMarvelChannelInfoMapper.queryUserChannelList(userChannelInfoParamDTO);
		} catch (Exception e) {
			throw new MarvelsBusinessException(e);
		}
	}

	@Override
	public UserChannelInfoResultDTO queryUserChannelDtoByCode(UserChannelInfoParamDTO userChannelInfoParamDTO)
			throws MarvelsBusinessException {
		try {
			if(StrUtil.isEmpty(userChannelInfoParamDTO.getChannelCode())){
				throw new MarvelsBusinessException("渠道code不能为空");
			}
			return UserMarvelChannelInfoMapper.queryUserChannelDtoByCode(userChannelInfoParamDTO.getChannelCode());
		} catch (Exception e) {
			throw new MarvelsBusinessException(e);
		}
	}

	@Override
	public UserChannelInfo queryUserChannelByCode(String channelCode) throws MarvelsBusinessException {
		try {
			if(StrUtil.isEmpty(channelCode)){
				throw new MarvelsBusinessException("渠道code不能为空");
			}
			return UserMarvelChannelInfoMapper.queryUserChannelByCode(channelCode);
		} catch (Exception e) {
			throw new MarvelsBusinessException(e);
		}
	}
	
	@Override
	public HSSFWorkbook downloadUserChannelExcel(UserChannelInfoParamDTO userChannelInfoParamDTO,
			HttpServletRequest request, HttpServletResponse response) throws MarvelsBusinessException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/vnd.ms-excel");
		//UserDTO user = CacheUtils.getCacheUser();
		userChannelInfoParamDTO.setUserCode(this.defaultRelationUser());
		List<UserChannelInfoResultDTO> list = UserMarvelChannelInfoMapper.queryUserChannelList(userChannelInfoParamDTO);
		HSSFWorkbook workbook  = getUserChannelExcel(list);
		return workbook;
	}
	
	public HSSFWorkbook getUserChannelExcel(List<UserChannelInfoResultDTO> list) {
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("入驻平台列表");
		HSSFRow row = sheet.createRow((int) 0);
		sheet.setDefaultColumnWidth(10);
		// 创建单元格，并设置值表头 设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		// 居中格式、加粗
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFFont font = wb.createFont();
		font.setFontHeightInPoints((short) 11);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		style.setBorderBottom((short) 1);// 下边框
		style.setBorderLeft((short) 1);// 左边框
		style.setBorderRight((short) 1);// 右边框
		style.setBorderTop((short) 1);// 上边框
		style.setLocked(true);
		style.setFont(font);
		// 设置表内容格式
		HSSFCellStyle style2 = wb.createCellStyle();
		style2.setBorderBottom((short) 1);// 下边框
		style2.setBorderLeft((short) 1);// 左边框
		style2.setBorderRight((short) 1);// 右边框
		style2.setBorderTop((short) 1);// 上边框
		style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("入驻平台");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("注册人数");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("H5链接");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("添加时间");
		cell.setCellStyle(style);
		
		List<UserChannelInfoResultDTO> datas = list;
		if (datas != null && datas.size() > 0) {
			for (int i = 0; i < datas.size(); i++) {
				UserChannelInfoResultDTO userChannelInfoResultDTO = list.get(i);
				row = sheet.createRow((int) i + 1);
				// 创建单元格，并设置值
				row.createCell(0).setCellValue(check(userChannelInfoResultDTO.getChannelName() + ""));
				row.createCell(1).setCellValue(check(userChannelInfoResultDTO.getRegisterNumber() + ""));
				row.createCell(2).setCellValue(check(userChannelInfoResultDTO.getChannelBaseUrl()));
				row.createCell(3).setCellValue(check(DateUtil.formatDateTime(userChannelInfoResultDTO.getCreatedDate())));
				for (int j = 0; j < 4; j++) {
					row.getCell(j).setCellStyle(style2);
				}
			}
		}
		return wb;
	}

	@Override
	public List<ChannelUserListResultDTO> queryChannelRegisterUserList(ChannelUserListParamDTO channelUserListParamDTO)
			throws MarvelsBusinessException {
		try {
			PageHelper.startPage(channelUserListParamDTO.getPageNo(), channelUserListParamDTO.getPageSize());
			return UserMarvelChannelInfoMapper.queryChannelRegisterUserList(channelUserListParamDTO);
		} catch (Exception e) {
			throw new MarvelsBusinessException(e);
		}
	}

	@Override
	public HSSFWorkbook downloadChannelRegisterUserExcel(ChannelUserListParamDTO channelUserListParamDTO,
			HttpServletRequest request, HttpServletResponse response) throws MarvelsBusinessException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/vnd.ms-excel");
		if(StrUtil.isNotEmpty(channelUserListParamDTO.getDateRange())){
			String [] date = channelUserListParamDTO.getDateRange().split(" - ");
			channelUserListParamDTO.setStartRegisterDate(date[0].trim());
			channelUserListParamDTO.setEndRegisterDate(date[1].trim());
		}
		List<ChannelUserListResultDTO> list = UserMarvelChannelInfoMapper.queryChannelRegisterUserList(channelUserListParamDTO);
		HSSFWorkbook workbook  = getChannelRegisterUserExcel(list);
		return workbook;
	}
	
	public HSSFWorkbook getChannelRegisterUserExcel(List<ChannelUserListResultDTO> list) {
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("渠道用户列表");
		HSSFRow row = sheet.createRow((int) 0);
		sheet.setDefaultColumnWidth(10);
		// 创建单元格，并设置值表头 设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		// 居中格式、加粗
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFFont font = wb.createFont();
		font.setFontHeightInPoints((short) 11);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		style.setBorderBottom((short) 1);// 下边框
		style.setBorderLeft((short) 1);// 左边框
		style.setBorderRight((short) 1);// 右边框
		style.setBorderTop((short) 1);// 上边框
		style.setLocked(true);
		style.setFont(font);
		// 设置表内容格式
		HSSFCellStyle style2 = wb.createCellStyle();
		style2.setBorderBottom((short) 1);// 下边框
		style2.setBorderLeft((short) 1);// 左边框
		style2.setBorderRight((short) 1);// 右边框
		style2.setBorderTop((short) 1);// 上边框
		style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("姓名");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("手机号码");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("贷款次数");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("放款次数");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("是否下载APP");
		cell.setCellStyle(style);
		cell = row.createCell(5);
		cell.setCellValue("注册时间");
		cell.setCellStyle(style);
		cell = row.createCell(6);
		cell.setCellValue("状态");
		cell.setCellStyle(style);
		
		List<ChannelUserListResultDTO> datas = list;
		if (datas != null && datas.size() > 0) {
			for (int i = 0; i < datas.size(); i++) {
				ChannelUserListResultDTO channelUserListResultDTO = list.get(i);
				row = sheet.createRow((int) i + 1);
				// 创建单元格，并设置值
				row.createCell(0).setCellValue(check(channelUserListResultDTO.getUserName() + ""));
				row.createCell(1).setCellValue(check(channelUserListResultDTO.getMobileNum() + ""));
				row.createCell(2).setCellValue(check(channelUserListResultDTO.getLoanNumber() + ""));
				row.createCell(3).setCellValue(check(channelUserListResultDTO.getLendNumber() + ""));
				row.createCell(4).setCellValue(check((channelUserListResultDTO.getIsDownloadApp() != null && channelUserListResultDTO.getIsDownloadApp() == 1)
						? "已下载" : "未下载"));
				row.createCell(5).setCellValue(check(DateUtil.formatDateTime(channelUserListResultDTO.getRegisterDate())));
				row.createCell(6).setCellValue(check(channelUserListResultDTO.getDeleteFlag() == 0 ? "正常" : "注销"));
				for (int j = 0; j < 7; j++) {
					row.getCell(j).setCellStyle(style2);
				}
			}
		}
		return wb;
	}

	@Override
	public String generatChannelCode() throws MarvelsBusinessException {
		String channelCode = RandomUtil.randomString(4);
		try {
			UserChannelInfoParamDTO userChannelInfoParamDTO = new UserChannelInfoParamDTO();
			userChannelInfoParamDTO.setChannelCode(channelCode);
			if(channelCode.equals("zrll") || this.queryUserChannelDtoByCode(userChannelInfoParamDTO) != null){
				MarvelsLogUtil.getInstance().info("channelCode：" + channelCode + ",已存在，重新生成新的channelCode");
				channelCode = this.generatChannelCode();
			}
		} catch (Exception e) {
			throw new MarvelsBusinessException(e);
		}
		MarvelsLogUtil.getInstance().info("channelCode：" + channelCode + ",生成success");
		return channelCode;
	}

	public String check(String row) {
		if (row == null) {
			row = "";
		} else if ("null".equals(row)) {
			row = "";
		}
		return row;
	}

	@Override
	public void saveUserChannelRelation(UserChannelRelationDTO dto) throws MarvelsBusinessException{
		try {
			//先删除后添加
			userChannelRelationMapper.deleteByChannelCode(dto.getChannelCode());
			for (UserChannelRelation userChannelRelation : dto.getRelationList()) {
				userChannelRelation.setChannelCode(dto.getChannelCode());
				userChannelRelationMapper.insertSelective(userChannelRelation);
			}
			//新增管理员关联
			UserChannelRelation userChannelRelation = new UserChannelRelation();
			userChannelRelation.setChannelCode(dto.getChannelCode());
			userChannelRelation.setRealName(this.defaultRelationUser());
			userChannelRelation.setUserCode(this.defaultRelationUser());
			userChannelRelationMapper.insertSelective(userChannelRelation);
			
			UserChannelInfo info=new UserChannelInfo();
			info.setChannelCode(dto.getChannelCode());
			info.setCpa(dto.getCpa());
			UserMarvelChannelInfoMapper.updateByChannelCode(info);
		} catch (Exception e) {
			throw new MarvelsBusinessException(e);
		}
	}

	@Override
	public Map<String, Object> selectUserChannelRelation(UserChannelRelationDTO dto)
			throws MarvelsBusinessException {
		try {
			Map<String,Object> map=new HashMap<String,Object>();
			List<UserChannelRelation> list=userChannelRelationMapper.selectByChannelCode(dto.getChannelCode(), this.defaultRelationUser());
			map.put("list", list);
			UserChannelInfoResultDTO infoResultDTO=UserMarvelChannelInfoMapper.queryUserChannelDtoByCode(dto.getChannelCode());
			map.put("infoResultDTO", infoResultDTO);
			return map;
		} catch (Exception e) {
			throw new MarvelsBusinessException(e);
		}
	}

	@Override
	public List<SysUserDTO> selectSysUserList() {
		SysUserParamDTO dto = new SysUserParamDTO();
		dto.setIgnoreUser(this.defaultRelationUser());
		
		String ignoreUserCodes= ServerProperties.getValue(configPropertiesPath, "common.properties", "ignore_user_code");
		if(StrUtil.isNotEmpty(ignoreUserCodes)){
			dto.setIgnoreUserCodeList(Arrays.asList(ignoreUserCodes.split(",")));
		}
		return consumerSystemApi.querySysUsers(dto);
	}
	
	private String defaultRelationUser(){
		String userCode = "admin";
		String defaultRelationUser = ServerProperties.getValue(configPropertiesPath, "common.properties", "channel_default_relation_user");
		if(StrUtil.isNotEmpty(defaultRelationUser)){
			userCode = defaultRelationUser;
		}
		return userCode;
	}
}
